package com.zhongxi.guoyuan.view.beanExchange;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.clearweed.ClearPayResult;
import com.zhongxi.guoyuan.entity.clearweed.ExchangeToPayResult;
import com.zhongxi.guoyuan.entity.clearweed.PersonExchangeResult;
import com.zhongxi.guoyuan.entity.coinStore.ItemGoodAttr;
import com.zhongxi.guoyuan.entity.pay.PayAliPayData;
import com.zhongxi.guoyuan.entity.pay.WeixinData;
import com.zhongxi.guoyuan.entity.user.center.UserExtendResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.DesTool;
import com.zhongxi.guoyuan.utils.MD5Tool;
import com.zhongxi.guoyuan.utils.PayUtils;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.view.personalCenter.ExchangePayActivity;
import com.zhongxi.guoyuan.view.rewardCoin.RewardAddressListActivity;
import com.zhongxi.guoyuan.zhifubao.PayResult;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PersonExchangePayActivity extends BaseActivity {


    @Bind(R.id.tv_edit_address)
    TextView mTvEditAddress;
    @Bind(R.id.rl_pres_Info)
    RelativeLayout mRlPresInfo;
    @Bind(R.id.ivPerson)
    ImageView mIvPerson;
    @Bind(R.id.tvUserName)
    TextView mTvUserName;
    @Bind(R.id.linearReceiver)
    LinearLayout mLinearReceiver;
    @Bind(R.id.tvPhone)
    TextView mTvPhone;
    @Bind(R.id.lienar_receiverPhone)
    LinearLayout mLienarReceiverPhone;
    @Bind(R.id.tvAddress)
    TextView mTvAddress;
    @Bind(R.id.relaReceiver)
    RelativeLayout mRelaReceiver;
    @Bind(R.id.rl_post_address)
    RelativeLayout mRlPostAddress;
    @Bind(R.id.textView6)
    TextView mTextView6;
    @Bind(R.id.tv_store_name)
    TextView mTvStoreName;
    @Bind(R.id.tv_store_phone)
    TextView mTvStorePhone;
    @Bind(R.id.tv_store_address)
    TextView mTvStoreAddress;
    @Bind(R.id.ll_self_address)
    LinearLayout mLlSelfAddress;
    @Bind(R.id.rl_address_info)
    RelativeLayout mRlAddressInfo;
    @Bind(R.id.tv_ispost)
    TextView mTvIspost;
    @Bind(R.id.tv_shopname)
    TextView mTvShopname;
    @Bind(R.id.tv_count)
    TextView mTvCount;
    @Bind(R.id.postcart_direction)
    ImageView mPostcartDirection;
    @Bind(R.id.rl_top_shopname)
    RelativeLayout mRlTopShopname;
    @Bind(R.id.ivImg)
    ImageView item_image;
    @Bind(R.id.tvName)
    TextView tv_itemname;
    @Bind(R.id.tvAttr)
    TextView tv_itemattr;
    @Bind(R.id.tvCash)
    TextView tv_itemcash;
    @Bind(R.id.tvRedbean)
    TextView tv_itemredBean;
    @Bind(R.id.tvNum)
    TextView tv_itemnum;
    @Bind(R.id.tv_notes)
    TextView mTvNotes;
    @Bind(R.id.ll_notes)
    LinearLayout mLlNotes;
    @Bind(R.id.tv_amountofmail)
    TextView mTvAmountofmail;
    @Bind(R.id.rl_postage)
    RelativeLayout mRlPostage;
    @Bind(R.id.tv_pay_tip)
    TextView mTvPayTip;
    @Bind(R.id.tv_innerbean)
    TextView mTvInnerbean;
    @Bind(R.id.tv_redbean)
    TextView mTvRedbean;
    @Bind(R.id.rela_true_pay)
    RelativeLayout mRelaTruePay;
    @Bind(R.id.et_pwd)
    EditText mEtPwd;
    @Bind(R.id.rela_edit_psd)
    RelativeLayout mRelaEditPsd;
    @Bind(R.id.tv_nowsave)
    TextView mTvNowsave;
    @Bind(R.id.tv_sure)
    TextView mTvSure;
    @Bind(R.id.tv_pay_award)
    TextView mTvAward;

    private String type;
    private String orderid;
    private ExchangeToPayResult.OrderInfo orderInfo;
    private ExchangeToPayResult.ShopInfo shopInfo;
    private ExchangeToPayResult.OrderCus orderCus;

    private String trueInner="0";
    private String trueRedbean="0";
    private String truePostage="0";
    private String mTotalRedbean;
    private String truePrice="0";
    private String goodsNumRed;
    private String mTrim;
    private UserExtendResult extendResult;
    private String mVerifycode;
    private String payResultOrderid;
    private PayAliPayData aliPayData;
    private WeixinData weixinData;
    private int index;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();//同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    //判断resultStatus为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        //该笔订单是否真实支付成功，需要依赖服务端的异步通知
                        showAlipaySuccessResult();
                    } else {
                        showAlipayResult(1);
                    }
                    break;
            }
        }
    };

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_person_exchange_pay);
        ButterKnife.bind(this);
        initTitle();
        tvTitle.setText("豆豆兑换确认");
        orderid=getIntent().getExtras().getString("orderid");
        CommonTool.hideSoft(mEtPwd,this);
        mTvEditAddress.setVisibility(View.GONE);
    }


    @Override
    protected void initData() {
        super.initData();
        initnowsave();
        getData();
    }

    private void getData() {
        type = "info";
        String str = "&orderid=" + orderid;
        getServer(Url.EXCHANGE_TOPAY, null, str, false, null, "get");
    }

    private void initnowsave() {
        String now = "您目前现存：" + MyApplication.getInstance().getInnerCurrency() + " 美豆/" + MyApplication.getInstance().getHdCurrency() + "红豆";
        mTvNowsave.setText(now);
    }

    @Override
    protected void initEvent() {
        super.initEvent();
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson=new Gson();
        if (type.equals("info")){
            ExchangeToPayResult mResult=gson.fromJson(response,ExchangeToPayResult.class);
            MyApplication.getInstance().setSpValue(mResult.getSafeobj());
            if (mResult.getOrderInfo() != null) {
                orderInfo=mResult.getOrderInfo();
            }
            if (mResult.getOrderCus()!=null){
                orderCus=mResult.getOrderCus();
            }
            if (mResult.getShopInfo()!=null){
                shopInfo=mResult.getShopInfo();
            }
            initinfo();
        }else if (type.equals("verifyCode")) {
            extendResult = gson.fromJson(response, UserExtendResult.class);
            MyApplication.getInstance().setSpValue(extendResult.getSafeobj());
            if (null != extendResult.getVerifycode() && !"".equals(extendResult.getVerifycode())) {
                mVerifycode = extendResult.getVerifycode();
             isEnough();
            } else {
                showShortToast("支付校验失败");
            }
        }else if ("topay".equals(type)) {
            ClearPayResult payResult= gson.fromJson(response, ClearPayResult.class);
            MyApplication.getInstance().setSpValue(payResult.getSafeobj());
            if (null != payResult && !"".equals(payResult)) {
                payResultOrderid = payResult.getOrderid();

                String securityKey = payResult.getSecurityKey();
                if (null != securityKey && !"".equals(securityKey)) {
                    String payParams = parseSecutiryKey(securityKey);
                    try {
                        JSONObject jsonObject = new JSONObject(payParams);
                        JSONObject alipay = jsonObject.optJSONObject("alipay");
                        aliPayData = PayAliPayData.parseObject(alipay);
                        JSONObject wechat = jsonObject.optJSONObject("wechat");
                        weixinData = WeixinData.parseObject(wechat);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    MyApplication.getInstance().sharedPrefrences.edit().putString("pay", "exchange").commit();

                    if (index == 0) {//微信支付
                        MyApplication.getInstance().sharedPrefrences.edit().putString("payredbean", orderInfo.getBackcashnum()).commit();

                        weixinPayRequest(weixinData);
                    } else if (index == 1) {//支付宝支付
                        zhifubaoPayRequest(aliPayData);
                    }
                } else {
                   showAlipaySuccessResult();
                }
            }
        }
    }

    public void zhifubaoPayRequest(PayAliPayData alipay) {
        PayUtils payUtils = new PayUtils(payResultOrderid,orderInfo.getGoodsname(), 6, CommonTool.getWhole(trueInner), CommonTool.getWhole(mTotalRedbean),truePostage, CommonTool.getWhole(truePrice));
        payUtils.zhifubaoPay(alipay, mHandler, PersonExchangePayActivity.this);
    }


    public void weixinPayRequest(WeixinData weixinData) {
        PayUtils payUtils=new PayUtils(payResultOrderid,orderInfo.getGoodsname(),6,CommonTool.getWhole(trueInner),CommonTool.getWhole(mTotalRedbean)
                ,truePostage,CommonTool.getWhole(truePrice),this,weixinData);
        payUtils.weixinPay();

    }

    private void initinfo() {

        if (orderInfo.getOrdertype().equals("1")){
            mRlPostAddress.setVisibility(View.VISIBLE);
            mLlSelfAddress.setVisibility(View.GONE);
            mRlTopShopname.setVisibility(View.VISIBLE);
            mTvAmountofmail.setVisibility(View.VISIBLE);


            if(null!=orderCus.getConsignee()&&!"".equals(orderCus.getConsignee())){
                mTvUserName.setText(orderCus.getConsignee());
            }else{
                mTvUserName.setText("");
            }
            if(null!=orderCus.getConsigneemphone()&&!"".equals(orderCus.getConsigneemphone())){
                mTvPhone.setText(orderCus.getConsigneemphone());
            }else{
                mTvPhone.setText("");
            }
            if(null!=orderCus.getShippingaddress()&&!"".equals(orderCus.getShippingaddress())){
                mTvAddress.setText(orderCus.getShippingaddress());
            }else{
                mTvAddress.setText("");
            }

            if(null!=orderInfo.getShouldpostage()&&!"".equals(orderInfo.getShouldpostage())){
                //不满足包邮
                if (DataUtil.moreThanOtherNoEqual(shopInfo.getAmountofmail(),DataUtil.multiplys(orderInfo.getRedbeanunitprice(),orderInfo.getGoodsnum(),2))){
                   if (orderInfo.getShouldpostage().equals("0")){
                       mTvAmountofmail.setVisibility(View.INVISIBLE);
                       mTvIspost.setVisibility(View.VISIBLE);
                   }else {
                       mTvAmountofmail.setText("运费"+orderInfo.getShouldpostage()+"红豆");
                       mTvIspost.setVisibility(View.GONE);
                   }
                }else {
                    mTvAmountofmail.setVisibility(View.INVISIBLE);
//                    mTvAmountofmail.setText("本店满"+shopInfo.getAmountofmail()+"元包邮");
                    mTvIspost.setVisibility(View.VISIBLE);
                }
            }
        }else {
            mRlPostAddress.setVisibility(View.GONE);
            mLlSelfAddress.setVisibility(View.VISIBLE);
            mRlTopShopname.setVisibility(View.INVISIBLE);
            mTvAmountofmail.setVisibility(View.INVISIBLE);

            if(null!=shopInfo.getName()&&!"".equals(shopInfo.getName())){
                mTvStoreName.setText(shopInfo.getName());
            }else{
                mTvStoreName.setText("");
            }
            if(null!=shopInfo.getPhone()&&!"".equals(shopInfo.getPhone())){
                mTvStorePhone.setText(shopInfo.getPhone());
            }else{
                mTvStorePhone.setText("");
            }
            if(null!=shopInfo.getAddress()&&!"".equals(shopInfo.getAddress())){
                mTvStoreAddress.setText(shopInfo.getAddress());
            }else{
                mTvStoreAddress.setText("");
            }
        }

        if(null!=shopInfo.getName()&&!"".equals(shopInfo.getName())){
            mTvShopname.setText("商家："+shopInfo.getName());
        }else{
            mTvShopname.setText("");
        }
        if (orderInfo.getGoodsname() != null && !"".equals(orderInfo.getGoodsname())) {
           tv_itemname.setText(orderInfo.getGoodsname());
        } else {
            tv_itemname.setText("");
        }
        if (orderInfo.getGoodsnum() != null && !"".equals(orderInfo.getGoodsnum())) {
            tv_itemnum.setText("x " + orderInfo.getGoodsnum());
        }
        parseGatter();

        Glide.with(context).load(Url.IMG_URL + orderInfo.getThumbnail()).placeholder(R.mipmap.iv_eg).fitCenter().into(item_image);

        String  redWhole=CommonTool.getWhole(DataUtil.multiplys(orderInfo.getRedbeanunitprice(),orderInfo.getGoodsnum(),2));
        String innerWhole = CommonTool.getWhole(DataUtil.multiplys(orderInfo.getInnerunitprice(),orderInfo.getGoodsnum(),2));
        if (orderInfo.getInnerunitprice() != null && !"0".equals(orderInfo.getInnerunitprice())&&orderInfo.getRedbeanunitprice()!=null&&!"0".equals(orderInfo.getRedbeanunitprice())) {
            tv_itemcash.setText( innerWhole+ " 美豆");
           tv_itemredBean.setText("+"+ redWhole + " 红豆");

            mTvAward.setVisibility(View.VISIBLE);
            if(null!=orderInfo.getBackcashnum()&&!"".equals(orderInfo.getBackcashnum())&&DataUtil.moreThanZero(orderInfo.getBackcashnum())){
                mTvAward.setText("（红豆不够现金补，兑成奖："+orderInfo.getBackcashnum()+"元）");
            }else{
                mTvAward.setText("（红豆不够现金补）");
            }
        }else if ( orderInfo.getInnerunitprice() != null && !"0".equals(orderInfo.getInnerunitprice())&& orderInfo.getRedbeanunitprice()!=null&&"0".equals(orderInfo.getRedbeanunitprice())){
            tv_itemcash.setText(innerWhole + " 美豆");
            tv_itemredBean.setText("");
            mTvAward.setVisibility(View.GONE);

        }else if (orderInfo.getInnerunitprice() != null && "0".equals(orderInfo.getInnerunitprice())&& orderInfo.getRedbeanunitprice()!=null&&!"0".equals(orderInfo.getRedbeanunitprice())){
            tv_itemcash.setText("");
            tv_itemredBean.setText(redWhole + " 红豆");
            mTvAward.setVisibility(View.GONE);

        }else {
            mTvAward.setVisibility(View.GONE);

        }




       if(null!=orderInfo.getRemark()&&!"".equals(orderInfo.getRemark())){
           mTvNotes.setText(orderInfo.getRemark());
       }else {
           mTvNotes.setText("无");
       }

        trueInner=innerWhole;
        if ("1".equals(orderInfo.getOrdertype()) ) {
            if (null != shopInfo.getAmountofmail() && !"".equals(shopInfo.getAmountofmail()) && !"0".equals(shopInfo.getAmountofmail())) {
                if (DataUtil.moreThanOther(DataUtil.multiplys(orderInfo.getRedbeanunitprice(), orderInfo.getGoodsnum(), 2), shopInfo.getAmountofmail())) {

                    mTotalRedbean= DataUtil.multiplys(orderInfo.getRedbeanunitprice(), orderInfo.getGoodsnum(), 2);

                    truePostage="0";
                } else {

                    mTotalRedbean= DataUtil.add(DataUtil.multiplys(orderInfo.getRedbeanunitprice(), orderInfo.getGoodsnum(), 2), orderInfo.getShouldpostage());
                    truePostage=orderInfo.getShouldpostage();
                }
            } else {

                mTotalRedbean= DataUtil.add(DataUtil.multiplys(orderInfo.getRedbeanunitprice(), orderInfo.getGoodsnum(), 2), orderInfo.getShouldpostage());
                truePostage=orderInfo.getShouldpostage();
            }

        }
        else {
            truePostage="0";
            mTotalRedbean= DataUtil.multiplys(orderInfo.getRedbeanunitprice(), orderInfo.getGoodsnum(), 2);
        }
        goodsNumRed = DataUtil.multiplys(orderInfo.getRedbeanunitprice(), orderInfo.getGoodsnum(), 2);


        //实际需支付的美豆数，红豆数
        if (DataUtil.moreThanZero(trueInner)&&DataUtil.moreThanZero(mTotalRedbean)){
            mTvInnerbean.setText(CommonTool.getWhole(trueInner)+"美豆");
            mTvRedbean.setText("+"+ CommonTool.getWhole(mTotalRedbean)+"红豆");
        }else if (DataUtil.moreThanZero(trueInner)&&!DataUtil.moreThanZero(mTotalRedbean)){
            mTvInnerbean.setText(CommonTool.getWhole(trueInner)+"美豆");
            mTvRedbean.setText("");
        }else if (!DataUtil.moreThanZero(trueInner)&&DataUtil.moreThanZero(mTotalRedbean)){
            mTvInnerbean.setText("");
            mTvRedbean.setText(CommonTool.getWhole(mTotalRedbean)+"红豆");
        }


        //美豆不够
        if (!DataUtil.moreThanOther(MyApplication.getInstance().getInnerCurrency(),trueInner)){
//            showMiedouNoEnough();
        }

            /*现存红豆大于等于总需支付红豆*/
        if (DataUtil.moreThanOtherNoEqual(MyApplication.getInstance().getHdCurrency(),mTotalRedbean)){

        }else {
            truePrice = DataUtil.subtract(mTotalRedbean, MyApplication.getInstance().getHdCurrency());
            mTotalRedbean= MyApplication.getInstance().getHdCurrency();
        }

    }

    private void verfycode() {
        type = "verifyCode";
        getServer(Url.MY_EXTEND_INFO, null, "", false, null, "get");
    }

    private void isEnough(){
       if (!DataUtil.moreThanZero(truePrice)){
            requestVf();
       }else {
           showHongdouNoBalance();
       }
    }
    private void requestVf() {
        type = "topay";
        Map<String, String> map = new HashMap<>();

        map.put("orderid",orderid);
        map.put("innerprice", CommonTool.getWhole(trueInner));

        //如果当前红豆大于商品需支付的红豆
        if (DataUtil.moreThanOtherNoEqual(MyApplication.getInstance().getHdCurrency(),goodsNumRed)){
            mTotalRedbean= CommonTool.getWhole(DataUtil.subtract(mTotalRedbean,truePostage));
            map.put("redbean",mTotalRedbean);
            map.put("postage",trueRedbean);
        }else {
            mTotalRedbean=CommonTool.getWhole(mTotalRedbean);
            truePostage="0";
            map.put("redbean", mTotalRedbean);
            map.put("postage",truePostage);
        }

        map.put("price", CommonTool.getWhole(truePrice));
        map.put("verifycode", mVerifycode);
        map.put("pwd", MyApplication.getInstance().descsc(mTrim));

        for (String key:map.keySet()) {
            Log.d("flag", "rightNowPay: key:"+key+":"+map.get(key));
        }

        getServer(Url.EXCHANGE_PAYVERIFY, map, "", false, null, "post");
    }

    private void parseGatter() {
        try {

            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(orderInfo.getGattr());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Iterator<String> keys = jsonObject.keys();
            String attr = "";
            while (keys.hasNext()) {
                String next = keys.next();
                String attrValue = jsonObject.optString(next);
                attr += attrValue + "/";
            }
            tv_itemattr.setText("规格："+ attr);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    private void showAlipayResult(int i) {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_exchange_noenough, null);
        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getWindow().setContentView(layout);

        TextView tvContent= (TextView) layout.findViewById(R.id.tvContent);
        TextView tvContent2= (TextView) layout.findViewById(R.id.tvContent2);

        if (i==1){
            tvContent.setText(getString(R.string.exchangeNoSuccessTip));
            tvContent2.setText(getString(R.string.exchangeNoSuccessContent));
        }
        TextView tvSurePay = (TextView) layout.findViewById(R.id.tvSurePay);
        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                startAct(MainHomeActivity.class);
            }
        });
        tvSurePay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                startAct(MainHomeActivity.class);
            }
        });

    }
    private void showAlipaySuccessResult() {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_exchange_paysuccess, null);
        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getWindow().setContentView(layout);


        TextView tvContent2= (TextView) layout.findViewById(R.id.tvContent2);
        tvContent2.setText("奖励您 "+ orderInfo.getBackcashnum() +" 元");

        TextView tvSurePay = (TextView) layout.findViewById(R.id.tvSurePay);


        tvSurePay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                startAct(MainHomeActivity.class);
            }
        });

    }
    /**
     * 红豆余额不足
     */
    private void showHongdouNoBalance() {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_order_hongdou, null);
        final android.support.v7.app.AlertDialog dialog = new android.support.v7.app.AlertDialog.Builder(context).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getWindow().setContentView(layout);
        TextView order_tvLess_hongdou = (TextView) layout.findViewById(R.id.order_tvLess_hongdou);
        order_tvLess_hongdou.setText(CommonTool.getWhole(truePrice) + " 红豆");
        TextView order_tvLess_yuan = (TextView) layout.findViewById(R.id.order_tvLess_yuan);
        order_tvLess_yuan.setText(CommonTool.getWhole(truePrice) + " 元");
        LinearLayout ll_aliPay = (LinearLayout) layout.findViewById(R.id.ll_aliPay);
        ll_aliPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (CommonTool.isFirstLongScroll()) {
                    if (!TextUtils.isEmpty(MyApplication.getInstance().getPhone())) {
                        requestVf();
                        index =1;
                    }else {
                        ToastUtil.show("您还没有绑定手机号,暂不能支付");
                    }

                }
                dialog.dismiss();
            }
        });
        LinearLayout ll_weichatPay = (LinearLayout) layout.findViewById(R.id.ll_weichatPay);
        ll_weichatPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (CommonTool.isFirstLongScroll()) {
                    if (!TextUtils.isEmpty(MyApplication.getInstance().getPhone())) {
                        requestVf();
                        index =0;
                    }else {
                        ToastUtil.show("您还没有绑定手机号,暂不能支付");
                    }
                }
                dialog.dismiss();
            }
        });
        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        //放弃支付
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                finish();
            }
        });

    }
    /**
     * 解析后台返回的支付商户信息
     *
     * @param securityKey
     */
    private String parseSecutiryKey(String securityKey) {
        String jsonStr = "";
        try {
            String sourcestr = MD5Tool.Md5(MyApplication.getInstance().getSk() + MyApplication.getInstance().getNow());
            String strs = URLDecoder.decode(securityKey, "UTF-8");
            jsonStr = DesTool.splitdecode(sourcestr, strs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonStr;
    }
    @OnClick({R.id.tv_edit_address, R.id.et_pwd, R.id.tv_sure,R.id.ivBack})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_edit_address:
//                Intent intent = new Intent(context, RewardAddressListActivity.class);
//                startActivityForResult(intent, 100);
                break;
            case R.id.tv_sure:
                mTrim = mEtPwd.getText().toString().trim();
                if (mTrim!=null&&!mTrim.isEmpty()){
                   verfycode();
                }
                break;
            case R.id.ivBack:
                onBackPressed();
                finish();
                break;
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            Log.d("flag", "ProcessFailResult: "+result.getCode());
            if (1000 == result.getCode()) {
                showShortToast("参数错误");
            }  else if (1557 == result.getCode()) {
                showShortToast("数量超限");
            } else if (1669 == result.getCode()) {
                showShortToast("红豆不足");
            }
            else if (2001 == result.getCode()) {
                showShortToast("库存不足");
            } else if (2005 == result.getCode()) {
                showShortToast("商品与 商品集合不匹配");
            } else if (2006 == result.getCode()) {
                showShortToast("商品集合数据格式错误");  //商品集合数据格式错误
            } else if (2007 == result.getCode()) {
                showShortToast("商品属性不在指定集合中");
            } else if (2008 == result.getCode()) {
                showShortToast("商品属性数据丢失， 请管理员调整");
            } else if (2009 == result.getCode()) {
                showShortToast("商品属性选择不完整");
            } else if (2013 == result.getCode()) {
                showShortToast("邮费错误");
            } else if (2015 == result.getCode()) {
                showShortToast("订单镜像丢失");
            } else if (2016 == result.getCode()) {
                showShortToast("订单定制信息已丢失");
            }else if (2019 == result.getCode()) {
                showShortToast("兑换数量超出每日限额");
            }else if (4003 == result.getCode()) {
                showShortToast("密码错误");
            }else if (5003 == result.getCode()) {
                showShortToast("美豆不足");
            } else if (5019 == result.getCode()) {
                showShortToast("选购商品数量超过库存");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }
}
